﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using log4net;
using CashFlow.Db.Entity;
using SysAdmin._00_Def;
using SysAdmin._03_Service._00_Db;
using SysAdmin._04_Form._00_Common;

namespace SysAdmin._04_Form._02_User
{
    public partial class UserForm : Form
    {
        private static ILog _logger = LogManager.GetLogger(typeof(UserForm));
        private string _copyText = "";

        public UserForm()
        {
            InitializeComponent();
        }

        private void UserForm_Load(object sender, EventArgs e)
        {
            dataGridView1.AutoGenerateColumns = false;
            label6.Text = "";
        }

        private void UserForm_Shown(object sender, EventArgs e)
        {
            dataGridView1.Height = ClientSize.Height - (Padding.Top + Padding.Bottom) - panel1.Height;
            label6.Location = new Point(panel1.Width - label6.Width, label6.Location.Y);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            LoadUsers();
        }

        private void LoadUsers()
        {
            try
            {
                string date = dateTimePicker1.Checked ? dateTimePicker1.Value.ToString("yyyy-MM-dd") : "";
                var ls = UserService.QueryAllByWhere(textBox1.Text.Trim()
                    , textBox2.Text.Trim()
                    , textBox3.Text.Trim()
                    , textBox4.Text.Trim()
                    , textBox5.Text.Trim()
                    , date).ToList();
                var ls2 = ls.Select(x => new DataGridItemData
                {
                    Id = x.UserInfo.Id,
                    Phone = x.UserInfo.Phone,
                    Name = x.UserInfo.Name,
                    InvitationCode = x.UserInfo.InvitationCode,
                    Reference = x.ReferenceUserInfo.Name,
                    ReferenceInvitationCode = x.UserInfo.ReferenceInvitationCode,
                    CreateTime = x.UserInfo.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")
                }).ToList();
                dataGridView1.DataSource = ls2;
                label6.Text = string.Format("会员人数: {0}", ls2.Count);
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                UICommonTool.ShowAlertDialog(ex.Message);
            }
        }

        private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex == 0)
                {
                    var cell = dataGridView1.Rows[e.RowIndex].Cells[0];
                    if ((bool)cell.FormattedValue == true)
                    {
                        cell.Value = false;
                    }
                    else
                    {
                        cell.Value = true;
                    }
                }
                else if (e.ColumnIndex == 8)
                {
                    var form = new UpdateUserForm();
                    string id = (string)dataGridView1.Rows[e.RowIndex].Cells[1].FormattedValue;
                    form.UserId = Convert.ToInt32(id);
                    DialogResult dr = form.ShowDialog();
                    if (dr == DialogResult.OK)
                    {
                        LoadUsers();
                    }
                }
                else if (e.ColumnIndex == 9)
                {
                    if (UICommonTool.ShowConfirmDialog("确定要删除吗？"))
                    {
                        try
                        {
                            string id = (string)dataGridView1.Rows[e.RowIndex].Cells[1].FormattedValue;
                            bool b = UserService.Delete(Convert.ToInt32(id));
                            ShopUserService.DeleteShopUserById(Convert.ToInt32(id));
                            if (b)
                            {
                                UICommonTool.ShowInfoDialog("删除成功！");
                                LoadUsers();
                            }
                            else
                            {
                                UICommonTool.ShowAlertDialog("删除失败！");
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.Error(ex);
                            UICommonTool.ShowAlertDialog("网络错误！");
                        }
                    }
                }
                else if (e.ColumnIndex == 10)
                {
                    int userId = (int)dataGridView1.Rows[e.RowIndex].Cells[1].Value;
                    var form = new ResetPwdForm();
                    form.UserId = userId;
                    form.ShowDialog();
                }
                else if (e.ColumnIndex == 11)
                {
                    int userId = (int)dataGridView1.Rows[e.RowIndex].Cells[1].Value;
                    var form = new UserAccountInfoForm();
                    form.UserId = userId;
                    form.ShowDialog();
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var form = new UserStructureForm();
            form.ShowDialog();
        }

        private class DataGridItemData
        {
            public int Id { get; set; }
            public string Phone { get; set; }
            public string Name { get; set; }
            public string InvitationCode { get; set; }
            public string Reference { get; set; }
            public string ReferenceInvitationCode { get; set; }
            public string CreateTime { get; set; }
        }

        private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right
                && e.RowIndex >= 0
                && (e.ColumnIndex >= 2 && e.ColumnIndex <= 6))
            {
                _copyText = (string)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
            }
        }

        private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Name == "toolStripMenuItem1")
            {
                UICommonTool.SetClipboardText(_copyText);
            }
        }
    }
}
